<template>
  <div id="app" class="min-h-screen bg-gray-50 flex flex-col">
    <!-- 全局通知组件 -->
    <div
        v-if="showNotification"
        class="fixed bottom-4 right-4 max-w-sm w-full bg-white shadow-lg rounded-lg overflow-hidden transform transition-all duration-300 ease-in-out z-50"
        :class="notificationType === 'success' ? 'border-l-4 border-green-500' :
              notificationType === 'error' ? 'border-l-4 border-red-500' :
              notificationType === 'warning' ? 'border-l-4 border-yellow-500' :
              'border-l-4 border-blue-500'"
    >
      <div class="p-4">
        <div class="flex">
          <div class="flex-shrink-0">
            <i
                :class="notificationType === 'success' ? 'fa fa-check-circle text-green-500' :
                      notificationType === 'error' ? 'fa fa-times-circle text-red-500' :
                      notificationType === 'warning' ? 'fa fa-exclamation-triangle text-yellow-500' :
                      'fa fa-info-circle text-blue-500'"
                class="h-6 w-6"
            ></i>
          </div>
          <div class="ml-3">
            <p class="text-sm font-medium text-gray-800">{{ notificationTitle }}</p>
            <p class="mt-1 text-sm text-gray-500">{{ notificationMessage }}</p>
          </div>
          <div class="ml-auto pl-3">
            <button
                class="inline-flex text-gray-400 hover:text-gray-500 focus:outline-none"
                @click="showNotification = false"
            >
              <i class="fa fa-times h-5 w-5"></i>
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 路由视图 - 所有页面都通过这里渲染 -->
    <router-view />
  </div>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted, provide } from 'vue';
import { useRouter } from 'vue-router';

// 用户菜单的ref引用，用于判断点击位置
const userMenuRef = ref(null);

// 用户信息状态
const userInfo = ref(null);

// 移动端菜单状态
const mobileMenuOpen = ref(false);

// 用户下拉菜单状态
const showUserMenu = ref(false);

// 未读通知数量
const unreadNotifications = ref(3);

// 全局通知状态
const showNotification = ref(false);
const notificationTitle = ref('');
const notificationMessage = ref('');
const notificationType = ref('info');

// 路由实例
const router = useRouter();

// 点击外部关闭菜单的处理函数
const handleClickOutside = (event) => {
  if (userMenuRef.value && !userMenuRef.value.contains(event.target)) {
    showUserMenu.value = false;
  }
};

// 切换用户菜单显示/隐藏
const toggleUserMenu = () => {
  showUserMenu.value = !showUserMenu.value;
};

// 页面加载时检查登录状态
onMounted(() => {
  // 实际项目中应该从API或本地存储获取用户信息
  checkLoginStatus();

  // 添加全局点击事件监听
  document.addEventListener('click', handleClickOutside);

  // 监听路由变化，关闭移动端菜单
  watch(
      () => router.currentRoute.value,
      () => {
        mobileMenuOpen.value = false;
        showUserMenu.value = false;
      }
  );
});

// 卸载时移除全局点击事件监听（防止内存泄漏）
onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside);
});

// 检查登录状态
const checkLoginStatus = () => {
  // 模拟从本地存储获取用户信息
  const storedUser = localStorage.getItem('currentUser');

  if (storedUser) {
    userInfo.value = JSON.parse(storedUser);
    // 如果已登录但在登录页，根据角色跳转到对应页面
    if (router.currentRoute.value.path === '/login') {
      if (userInfo.value.role === 'ADMIN') {
        router.push('/admin/dashboard');
      } else {
        router.push('/account');
      }
    }
  }
  // 移除强制跳转到登录页的逻辑，允许用户自由访问页面
};

// 处理路由页面的操作按钮
const handleRouteAction = (action) => {
  if (action.callback) {
    action.callback();
  } else if (action.route) {
    router.push(action.route);
  }
};

// 显示全局通知
const showGlobalNotification = (title, message, type = 'info', duration = 5000) => {
  notificationTitle.value = title;
  notificationMessage.value = message;
  notificationType.value = type;
  showNotification.value = true;

  // 自动关闭
  if (duration > 0) {
    setTimeout(() => {
      showNotification.value = false;
    }, duration);
  }
};

// 用户操作
const goToProfile = () => {
  showUserMenu.value = false;
  router.push('/profile');
  showGlobalNotification('提示', '个人资料页面即将打开', 'info');
};

const changePassword = () => {
  showUserMenu.value = false;
  router.push('/change-password');
  showGlobalNotification('提示', '密码修改页面即将打开', 'info');
};

const logout = () => {
  showUserMenu.value = false;
  if (confirm('确定要退出登录吗？')) {
    // 清除用户信息
    localStorage.removeItem('currentUser');
    userInfo.value = null;
    router.push('/login');
    showGlobalNotification('成功', '您已成功退出登录', 'success');
  }
};

// 提供全局通知方法给子组件
provide('showNotification', showGlobalNotification);
</script>

<style>
/* 全局样式 */
#app {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
}

/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a1a1a1;
}

/* 平滑滚动 */
html {
  scroll-behavior: smooth;
}

/* 基础动画 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter, .fade-leave-to {
  opacity: 0;
}
</style>